#include <stdio.h>
#include <stdlib.h>
#include "mpi.h"

#define COUNT 5

int main(int argc, char **argv)
{
    MPI_Datatype newtype;
    int wsize, rank;
    int arr[COUNT * 3], i;
    int failure = 0;
    MPI_Status status;

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &wsize);

    if (wsize != 2)
    {
        fputs("Should be run with 2 processes\n", stderr);
        exit(1);
    }

    /* declare contiguous type */
    MPI_Type_contiguous(COUNT, MPI_INT, &newtype);

    /* commit test */
    fputs("Committing Type\n", stderr);
    MPI_Type_commit(&newtype);

    if (rank == 0)
    {
        /* fill array with numbers */
        for (i = 0; i < (COUNT * 3); i++)
            arr[i] = i + 1;

        /* send data to process 1 */
        fputs("Sending data:\n", stdout);
        for (i = 0; i < (COUNT * 3); i++)
        {
            fprintf(stdout, "%i ", arr[i]);
            if (arr[i] != (i + 1))
                failure = 1;
        }
        fputs("\n", stdout);

        MPI_Send(arr, 3, newtype, 1, 9, MPI_COMM_WORLD);
    }
    else if (rank == 1)
    {
        /* receive data from process 0 */
        MPI_Recv(arr, 3, newtype, 0, 9, MPI_COMM_WORLD, &status);

        /* print and verify data */
        fputs("Received data:\n", stdout);
        for (i = 0; i < (COUNT * 3); i++)
        {
            fprintf(stdout, "%i ", arr[i]);
            if (arr[i] != (i + 1))
                failure = 1;
        }
        fputs("\n", stdout);
    }
    
    if (failure)
        fputs("FAILURE\n", stderr);
    else
        fputs("SUCCESS\n", stderr);

    MPI_Finalize();

    return(0);
}

